#include "UTF8String.h"

#include <iostream>
#include <string>

using namespace std;

utf8string::utf8string(const string& str)
{
	data = str;
	refresh();
}

utf8string::utf8string(const char* str)
{
	data = string(str);
	refresh();
}

utf8string::~utf8string()
{
	delete[] offerset;
}

string utf8string::stlstring()
{
	return data;
}

const char* utf8string::c_str()
{
	return data.c_str();
}

utf8string utf8string::operator +(utf8string& ustr)
{
	string temp = data + ustr.stlstring();

	return utf8string(temp);
}

int utf8string::length()
{

	return _length;
}

string utf8string::get(int index)
{
	if(index >= _length) return "";
	string temp = data.substr(offerset[index], offerset[index+1] - offerset[index]);

	return temp;
}

string utf8string::operator [](int index)
{
	if(index >= _length) return "";
	string temp = data.substr(offerset[index], offerset[index+1] - offerset[index]);

	return temp;
}

string utf8string::substr(int u8_start_index, int u8_length)
{
	if(u8_start_index + u8_length >= _length) return "";

	return data.substr(offerset[u8_start_index], offerset[u8_start_index+u8_length] - offerset[u8_start_index]);
}

utf8string utf8string::utf8substr(int u8_start_index, int u8_length)
{
	if(u8_start_index + u8_length >= _length) return utf8string("");
	string ret = data.substr(offerset[u8_start_index], offerset[u8_start_index+u8_length] - offerset[u8_start_index]);

	return utf8string(ret);
}

void utf8string::refresh()
{
	int *tmp = new int[data.length()];
	int i, tmpidx = 0;
	for(i = 0; i < data.length(); i++)
	{
		if(((int)data[i] > 0)||(!(((int)data[i] & 0x00000040) == 0)))
		{
			tmp[tmpidx] = i;
			tmpidx++;
		}
	}

	tmp[tmpidx] = data.length();

	int *tmp2 = new int[tmpidx];
	for(i = 0; i < tmpidx; i++)
	{
		tmp2[i] = tmp[i];
	}


	delete[] tmp;
	offerset = tmp2;
	_length = tmpidx;
}
